/*
 * @Description: 路由回退组件，用于刷新后请求导航数据
 * @Author: Rfan
 * @Date: 2022-11-17 15:02:16
 * @LastEditTime: 2022-11-17 19:44:07
 */

import { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { observer } from 'mobx-react-lite';
import { appState } from '@/store/mobx';
import { routerActions, routerState } from '@/store/routerStore';
import { selectItemByKey } from '@/utils/list';
import Layout from '@/layout';

const FullbackRouter = () => {
  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    if (appState.token) {
      console.log('flag', routerState.navReqFlag);
      if (!routerState.navReqFlag) {
        routerActions
          .getNavList()
          .then((res: any) => {
            const rightRouter = selectItemByKey(location.pathname, res, 'rightsLink');
            console.log('rightRouter:', { rightRouter });
            if (rightRouter) {
              navigate(location.pathname, { replace: true });
            } else {
              navigate('/404', { replace: true });
            }
          })
          .catch(() => {
            navigate('/404', { replace: true });
          });
      }
    } else {
      navigate('/404', { replace: true });
    }
  }, []);

  return (
    <>
      {routerState.noLayoutList.indexOf(location.pathname) < 0 && routerState.navReqFlag ? (
        <Layout />
      ) : null}
    </>
  );
};

export default observer(FullbackRouter);
